package mo.leetcode_top;

import java.util.*;

public class L127 {

    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> wordSet = new HashSet<>(wordList);
        if (!wordSet.contains(endWord)) {
            return 0;
        }
        Map<String, Integer> path = new HashMap<>();
        path.put(beginWord, 1);
        Queue<String> queue = new LinkedList<>();
        queue.add(beginWord);
        while (!queue.isEmpty()) {
            String word = queue.poll();
            for (int i = 0; i < word.length(); i++) {
                for (char j = 'a'; j <= 'z'; j++) {
                    StringBuilder builder = new StringBuilder(word);
                    builder.setCharAt(i, j);
                    String newWord = builder.toString();
                    if (newWord.equals(endWord)) {
                        return path.get(word) + 1;
                    }
                    if (wordSet.contains(newWord) && !path.containsKey(newWord)) {
                        queue.add(newWord);
                        path.put(newWord, path.get(word)+1);
                    }
                }
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        L127 test = new L127();
        System.out.println(test.ladderLength("hit", "cog",
                Arrays.asList("hot","dot","dog","lot","log")));
    }
}
